//
//  UIView+HKToast.m
//  HKProject
//
//  Created by 胡锦涛 on 2020/5/22.
//  Copyright © 2020 胡锦涛. All rights reserved.
//

#import "UIView+HKToast.h"
#import <objc/message.h>

#define  KHK_FONT_SIZE (17.0)
#define  KHK_ANIMATION_TIME (0.1)
#define  KHK_DURING (1.5)
@interface UIView ()

/** loading view */
@property (nonatomic, strong) UILabel *tipLabel;
/** loading view */
@property (nonatomic, strong) UIActivityIndicatorView *hk_loadingView;

@end
@implementation UIView (HKToast)
static void *hk_loadingViewKey = &hk_loadingViewKey;
- (UIActivityIndicatorView *)hk_loadingView {
    return objc_getAssociatedObject(self, &hk_loadingViewKey);
}
-(void)setHk_loadingView:(UIActivityIndicatorView *)hk_loadingView {
    objc_setAssociatedObject(self, &hk_loadingViewKey, hk_loadingView, OBJC_ASSOCIATION_RETAIN);
}
static void *tipLabelKey = &tipLabelKey;
- (UILabel *)tipLabel {
     return objc_getAssociatedObject(self, &tipLabelKey);
}
- (void)setTipLabel:(UILabel *)tipLabel {
    objc_setAssociatedObject(self, &tipLabelKey, tipLabel, OBJC_ASSOCIATION_RETAIN);
}


/**
 展示loading（默认灰色）
 */
- (void)hk_showLoading {
    // 默认展示灰色loading
    [self hk_showLoadingWithColor:[UIColor grayColor] text:@""];
}
- (void)hk_showLoadingAfterDelay:(CGFloat)duration {
    [self hk_showLoading];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self hk_removeLoading];
    });
    
}
- (void)hk_showLoadingWithText:(NSString*)text {
    // 默认展示灰色loading
    [self hk_showLoadingWithColor:[UIColor grayColor] text:text];
}
- (void)hk_showLoadingWithText:(NSString*)text afterDelay:(CGFloat)duration {
    [self hk_showLoadingWithText:text];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self hk_removeLoading];
    });
}
/**
 展示指定颜色的loading

 @param color loading的颜色
 */
- (void)hk_showLoadingWithColor:(UIColor *)color text:(NSString*)title{
    if (self.hk_loadingView) {
        [self.hk_loadingView removeFromSuperview];
        self.hk_loadingView = nil;
    }
    self.hk_loadingView = [[UIActivityIndicatorView alloc] initWithFrame:self.bounds];
    CGAffineTransform transform = CGAffineTransformMakeScale(1.2f, 1.2f);
    self.hk_loadingView.transform = transform;
    [self addSubview:self.hk_loadingView];
    if (title != nil && title.length > 0) {
        self.tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 30)];
        self.tipLabel.center = CGPointMake(self.center.x, self.center.y + 28);
        self.tipLabel.text = title;
        self.tipLabel.textAlignment = NSTextAlignmentCenter;
        self.tipLabel.textColor = [UIColor grayColor];
        self.tipLabel.font = [UIFont systemFontOfSize:14];
        //self.tipLabel.backgroundColor = [UIColor blueColor];
        [self addSubview:self.tipLabel];
        self.tipLabel.hidden = NO;
    }
    self.hk_loadingView.color = color;
    [self.hk_loadingView startAnimating];
    self.hk_loadingView.userInteractionEnabled = NO;
}

/**
 移除loading
 */
- (void)hk_removeLoading {
    if (self.hk_loadingView) {
        [self.hk_loadingView removeFromSuperview];
        self.hk_loadingView = nil;
    }
    if (self.tipLabel) {
        [self.tipLabel removeFromSuperview];
        self.tipLabel = nil;
    }
}


- (void)hk_toast:(NSString *)msg{
    [self hk_toast:msg during:KHK_DURING];
}

- (void)hk_toast:(NSString *)msg postion:(HK_TOAST_POSTION)postion{
    [self hk_toast:msg during:KHK_DURING postion:postion];
}

- (void)hk_toast:(NSString *)msg type:(HK_TOAST_TYPE)type{
    [self hk_toast:msg during:KHK_DURING postion:HK_TOAST_BOTTOM type:type];
}

- (void)hk_toast:(NSString *)msg postion:(HK_TOAST_POSTION)postion type:(HK_TOAST_TYPE)type{
    [self hk_toast:msg during:KHK_DURING postion:postion type:type];
}

- (void)hk_toast:(NSString *)msg during:(NSTimeInterval)during{
    [self hk_toast:msg during:KHK_DURING postion:HK_TOAST_MIDDLE];
}

- (void)hk_toast:(NSString *)msg during:(NSTimeInterval)during postion:(HK_TOAST_POSTION)postion{
    [self hk_toast:msg during:KHK_DURING postion:postion type:HK_TOAST_WHITE_FONT];
}

- (void)hk_toast:(NSString *)msg during:(NSTimeInterval)during postion:(HK_TOAST_POSTION)postion type:(HK_TOAST_TYPE)type{
    [self createContentLabWithMessage:msg during:during postion:postion type:type];
}

- (UILabel*)createContentLabWithMessage:(NSString*)msg during:(NSTimeInterval)during postion:(HK_TOAST_POSTION)postion type:(HK_TOAST_TYPE)type{
    self.userInteractionEnabled = NO;
    CGSize      screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat     contentLabY = 0.0;
    UIColor   * fontColor = nil;
    UIColor   * backColor = nil;
    
    switch (postion) {
        case HK_TOAST_TOP:
            contentLabY = 100.0;
            break;
        case HK_TOAST_MIDDLE:
            contentLabY = screenSize.height / 2.0;
            break;
        case HK_TOAST_BOTTOM:
            contentLabY = screenSize.height - 100.0;
        break;
        default:
            break;
    }
    
    switch (type) {
        case HK_TOAST_WHITE_FONT:
            fontColor = [UIColor whiteColor];
            backColor = [UIColor blackColor];
            break;
        case HK_TOAST_BLACK_FONT:
            fontColor = [UIColor blackColor];
            backColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1.0];
        default:
            break;
    }
    
    CGFloat     pading = 20.0;
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    CGSize      msgSize = [msg sizeWithFont:[UIFont systemFontOfSize:KHK_FONT_SIZE]
                          constrainedToSize:CGSizeMake(MAXFLOAT, 0)];
#pragma clang diagnostic pop
    CGFloat     contentLabWidth = msgSize.width + pading * 2.0;
    NSInteger   multiple = (NSInteger)(msgSize.width / (screenSize.width - pading * 2.0)) + 1;
    if(multiple > 1){
        contentLabWidth = screenSize.width - pading * 2.0;
    }
    UILabel * contentLab = [[UILabel alloc]initWithFrame:CGRectMake((screenSize.width - contentLabWidth) / 2.0,contentLabY,contentLabWidth,multiple * msgSize.height + pading)];
    contentLab.numberOfLines = 0;
    contentLab.backgroundColor = backColor;
    contentLab.textColor = fontColor;
    contentLab.font = [UIFont systemFontOfSize:KHK_FONT_SIZE];
    contentLab.textAlignment = NSTextAlignmentCenter;
    contentLab.center = CGPointMake(screenSize.width / 2.0, contentLabY);
    contentLab.text = msg;
    contentLab.layer.cornerRadius = 8.0;
    contentLab.layer.masksToBounds = YES;
    contentLab.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [self addSubview:contentLab];
    [UIView animateWithDuration:KHK_ANIMATION_TIME animations:^{
        contentLab.transform = CGAffineTransformMakeScale(1.2, 1.2);
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            contentLab.transform = CGAffineTransformIdentity;
        }completion:^(BOOL finished) {
            [self performSelector:@selector(clearContentLab:) withObject:contentLab afterDelay:during];
        }];
        
    }];
    return contentLab;
}

- (void)clearContentLab:(UILabel *)contentLab{
    
    [UIView animateWithDuration:KHK_ANIMATION_TIME animations:^{
        contentLab.transform = CGAffineTransformMakeScale(0.5, 0.5);
    } completion:^(BOOL finished) {
        [contentLab removeFromSuperview];
        self.userInteractionEnabled = YES;
    }];
}
@end
